import React from 'react';
import { HomeOutlined, UserOutlined,ExclamationCircleOutlined } from '@ant-design/icons';
import {Link} from 'react-router-dom';
import { Table,Breadcrumb,Button,Input,Modal,message,Select,Form,Upload,Result} from 'antd';
import {connect} from 'react-redux'
import { LoadStudentActionAsync,DeleteStudentActionAsync,AddStudentActionAsync} from '../../../redux/action/studentAction';
import http from '../../../service/http';
import { GetUserName } from '../../../common/auth';
import config from '../../../config'

const {Option}=Select
const ButtonStyle={margin:"15px"}



function Student(props) {
  const [selectedRowKeys,setSelectedRowKeys]=React.useState([])
  const [search,setSearch]=React.useState('')
  const [searchType,setSearchType]=React.useState('studentName')
  const [editVisible,setEditVisible]=React.useState(false)
  const [editMessage,setEditMessage]=React.useState({})
  const [page,setPage]=React.useState(1)
  const [per,setPer]=React.useState(-1)
  const onSelectChange = selectedRowKeys => {
    setSelectedRowKeys(selectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  }
  React.useEffect(()=>{
    props.LoadStudentActionAsync({})
    http.getUser({username:GetUserName()}).then((res)=>{
      if(res.code!==200)return
      setPer(res.data.per)
    })
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])
  const columns = [
    {
      title: '姓名',
      dataIndex: 'studentName',
      ellipsis:true,
      align:'center',
      sorter: (a, b) => a.id - b.id,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      ellipsis:true,
      align:'center',
    },
    {
      title: '学号',
      dataIndex: 'studentId',
      ellipsis:true,
      align:'center',
    },
    {
      title: '班级',
      dataIndex: 'className',
      ellipsis:true,
      align:'center',
    },
    {
      title: '宿舍',
      dataIndex: 'dorm',
      ellipsis:true,
      align:'center',
    },
    {
      title:'编辑',
      dataIndex:'edit',
      ellipsis:true,
      align:'center',
      render:(edit,row)=>{
        return(<div>
          <Button type='primary' onClick={()=>{
            setEditMessage({
              title:'修改学生',
              okText:'修改',
              data:row,
              successMessage:'修改成功',
              errorMessage:'修改失败'
            })
            setEditVisible(true)
          }}>编辑</Button>
        </div>)
      }
    }
  ];
  return (
    per===-1?<div>
    </div>:per===1?
    <div>
      <Result
        status="403"
        title="403"
        subTitle="Sorry,你没有访问此页面的权限."
      />
    </div>
    :
    <div style={{padding:'15px'}}>
      <Breadcrumb>
        <Breadcrumb.Item>
          <HomeOutlined />
          <Link to='/home'>首页</Link>
        </Breadcrumb.Item>
        <Breadcrumb.Item>
          <UserOutlined />
          <Link to='/home/student1'>学生信息</Link>
        </Breadcrumb.Item>
      </Breadcrumb>
      <hr/>
      <div style={{background:'#fafafa',marginTop:'15px'}}>
      <Button type="primary" style={ButtonStyle} onClick={()=>{
        setEditMessage({
          title:'添加学生',
          okText:'添加',
          successMessage:'添加成功',
          errorMessage:'添加失败',
          data:null
        })
        setEditVisible(true)
      }}>添加</Button>
      <Button type="danger" style={ButtonStyle}
        onClick={()=>{
          if(selectedRowKeys.length===0){
            message.info('请至少选择一条数据！')
          }else{
            Modal.confirm({
              title: '提示',
              icon: <ExclamationCircleOutlined />,
              content: '你确定要删除吗?',
              okText: '确认',
              okType: 'danger',
              cancelText: '取消',
              onOk() {
                props.DeleteStudentActionAsync({id:selectedRowKeys}).then((res)=>{
                  if(search===''){
                    props.LoadStudentActionAsync({pageNum:page})
                  }else{
                    props.LoadStudentActionAsync({[searchType]:search})
                  }
                })
              }
            });
          }
        }}
      >删除</Button>
      <Select defaultValue="studentName" style={{ width: '100px' ,marginLeft:'15px',marginRight:'15px',borderRight:'none'}} onChange={(value)=>{setSearchType(value)}}>
        <Option value="studentName">姓名</Option>
        <Option value="studentId">学号</Option>
        <Option value="className">班级</Option>
      </Select>
      <Input.Search
        placeholder="请输入"
        enterButton
        size="middle"
        onSearch={(value)=>{
          setSearch(value)
          props.LoadStudentActionAsync({[searchType]:value})
        }}
        style={{marginTop:'15px',width:'300px'}}
      />
      {/* <Button style={ButtonStyle} type="primary"
        onClick={()=>{
          props.LoadStudentActionAsync()
        }}
      >重置</Button> */}
      <Upload
        name='file'
        // action='/api/student/import'
        action={config.reqBaseUrl+'/student/import'}
        onChange={(info)=>{
          if(info.file.response&&info.file.response.msg==="成功"){
            message.success('导入成功')
            props.LoadStudentActionAsync()
          }
        }}
        showUploadList={false}
      >
        <Button type='danger' style={{marginLeft:'30px'}}>导入</Button>
      </Upload>,
      <Button style={{margin:'15px 0 0 15px'}}
        type="primary"
        onClick={
          ()=>{
            Modal.confirm({
              title: '提示',
              icon: <ExclamationCircleOutlined />,
              content: '你确定要导出Excel表格吗?',
              okText: '确认',
              cancelText: '取消',
              onOk() {
                // const url="http://193.112.118.108/api/student/export"
                // const url ="http://localhost:8080/student/export"
                const url =config.ip+config.reqBaseUrl+"/student/export"
                window.location.href=url
              }
            });
          }
        }
      >导出</Button>
      </div>
      <Table rowSelection={rowSelection} columns={columns} 
        dataSource={props.studentList.records}
        rowKey="id"
        pagination={
          {
            pageSize:8,
            total:props.studentList.total,
            onChange:(pageNum,pageSize)=>{
              setPage(pageNum)
              props.LoadStudentActionAsync({pageNum:pageNum,pageSize:pageSize})
            }
          }
        }
        locale={
          {
            cancelSort:'点击取消排序',
            triggerAsc:'点击升序',
            triggerDesc:'点击降序'
          }
        }
      />
      <Edit
        visible={editVisible}
        close = {()=>{setEditVisible(false)}}
        message={editMessage}
        AddStudentActionAsync={props.AddStudentActionAsync}
        LoadStudentActionAsync={props.LoadStudentActionAsync}
        page={page}
      ></Edit>
    </div>
  )
}
//使用connect()()创建并暴露一个Count的容器组件
export default connect(
	state => ({
    studentList:state.studentList
	}),
	{LoadStudentActionAsync,DeleteStudentActionAsync,AddStudentActionAsync}
)(Student)
//更新和添加学生组件

function Edit(props) {
  const [editFrom]=Form.useForm()
  React.useEffect(()=>{
    if(props.message.data){
        editFrom.setFieldsValue(props.message.data)
      }
      else{
        if(editFrom){
          editFrom.resetFields()
        }
      }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[props.message.data])
  return (
    <div>
      <Modal visible={props.visible} onCancel={()=>{props.close()}}
        forceRender
        okText={props.message.okText}
        title={props.message.title}
        cancelText='取消'
        onOk={async () => {
          try{
            let fieldsValue = await editFrom.validateFields()
            if(props.message.data){
              fieldsValue={id:props.message.data.id,...fieldsValue}
            }
            await props.AddStudentActionAsync(fieldsValue)
            props.LoadStudentActionAsync({pageNum:props.page})
            props.close()
            editFrom.resetFields()
            message.success(props.message.successMessage)
          }
          catch{
            message.error(props.message.errorMessage)
          }
        }}
      >
        <Form
          layout="horizontal"
          form={editFrom}
          name="editForm"
        >
          <Form.Item
            name="studentName"
            label="姓名"
            rules={[
              {
                min:2,
                message: '请输入大于等于2个字符！',
              },
              {
                required: true,
                message: '请输入姓名',
              },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder='姓名' />
          </Form.Item>
          <Form.Item
            name="sex"
            label="姓别"
            initialValue='男'
            rules={[
                {
                required: true,
              }
            ]}
          >
            <Select>
              <Option value='男'>男</Option>
              <Option value='女'>女</Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="studentId"
            label="学号"
            rules={[
              {
                pattern:/^\d{4,20}$/,
                message: '请输入大于等于4个数字！',
              },
              {
                required: true,
                message: '请输入学号',
              },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder='学号' />
          </Form.Item>
          <Form.Item
            name="className"
            label="班级"
            rules={[
              {
                min:2,
                message: '请输入大于等于2个字符！',
              },
              {
                required: true,
                message: '请输入班级',
              },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder='班级' />
          </Form.Item>
          <Form.Item
            name="dorm"
            label="宿舍"
            rules={[
              {
                min:2,
                message: '请输入大于等于2个字符！',
              },
              {
                required: true,
                message: '请输入宿舍',
              },
            ]}
          >
            <Input prefix={<UserOutlined />} placeholder='宿舍' />
          </Form.Item>
      </Form>
      </Modal>
    </div>
  )
}